<template>
  <div>
    <a-form :model="formState" ref="userBusCompany">
      <a-form-item name="companyIds">
        <a-transfer :dataSource="companyList" v-model="formState.companyIds" :listStyle="{ width: '45%', height: '480px' }" :titles="[' 可选合作企业', ' 已选合作企业']" :render="(item) => item.title" :target-keys="formState.companyIds" @change="handleTransferChange" filterable></a-transfer>
      </a-form-item>
    </a-form>
  </div>
</template>
<script lang="ts" name="UserBusCompany" setup>
import { reactive, ref } from 'vue';
import { getBusCompanyList, querySetCompany, setBusCompany } from '@/views/sys/user/data/user.api';

const userBusCompany = ref();
const companyList = ref();
const userId = ref();
const formState = reactive({
  companyIds: [],
});

/**
 * 设置数据
 * @param data
 */
async function setData(data) {
  userId.value = data.record.userId;
  let companyIds = await querySetCompany({
    userId: userId.value,
  });
  getBusCompanyList({}).then((data) => {
    data.map((item) => {
      item.key = item.companyId;
      item.title = item.companyName;
    });
    companyList.value = data;
    formState.companyIds = companyIds;
  });
}

/**
 * 穿梭框change
 * @param targetKeys
 * @param direction
 * @param moveKeys
 */
function handleTransferChange(targetKeys, direction, moveKeys) {
  formState.companyIds = targetKeys;
}

/**
 * 提交已分配企业
 */
async function handleSubmit(drawerEmit) {
  userBusCompany.value.validate().then(async () => {
    await setBusCompany({
      userId: userId.value,
      busCompanyIds: formState.companyIds.join(','),
    });
    //刷新列表
    drawerEmit('success', {
      isUpdate: false,
      values: {},
    });
  });
}

/**
 * 暴露给父组件调用的方法
 */
defineExpose({
  setData,
  handleSubmit,
});
</script>
